<?php
namespace App\Admin\Requests\System;

use Closure;
use Illuminate\Validation\ValidationException;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Hash;
use App\Admin\Models\User;

class MenuCreateRequest extends FormRequest
{

    public function rules(): array
    {
        return [
            'parent_id' => 'required|nullable|exists:system_menu,id',
            'type'      => 'required|in:M,B,L,I',
            'title'     => 'required|string',
            'icon'      => 'sometimes|nullable|string',

            'name'      => 'required|nullable|string',
            'path'      => [
                'required', 
                'nullable', 
                'string', 
                function (string $attribute, mixed $value, Closure $fail){
                    if( !str_starts_with($value, '/') ){
                        $fail("{$attribute}必须以/开头");
                    }
                },
            ],
            'component' => 'required|nullable|string',

            'sort'      => 'required|integer|between:0,10000',
            'is_hidden' => 'required|integer|boolean',
        ];
    }

    public function attributes()
    {
        return [
            'path' => 'vue路径',
        ];
    }

    public function messages()
    {
        return [
            'login_name.required' => ':attribute不能为空',
        ];
    }

    protected function prepareForValidation(): void
    {
        $name = $this->input('name');
        $path = $this->input('path');
        $component = $this->input('component');
        $this->merge([
            'name' => empty($name) ?  Str::camel(str_replace('/', '_', $component)) : $name ,
            'path' => empty($path) ?  '/'.$component : $path ,
        ]);
    }
}
